<template>
	<div class="system-role_list-container layout-padding" style="overflow-y:auto">
		<!-- <el-card shadow="hover" class="layout-padding-auto"> -->
		<el-card shadow="hover">
			<div class="bar_btn_div">
				<div class="title_div">
					<div>筛选</div>
				</div>
				<div>
					<el-button size="default" @click="handleResetSearch()">重置搜索</el-button>
					<el-button type="primary" size="default" @click="refresh()">查询搜索
					</el-button>
				</div>
			</div>
			<div class="search_div">
				<el-form :model="state.ruleForm" label-width="120px">
					<div style="display: flex; flex-wrap: wrap">
						<el-form-item label="模板编码">
							<el-input v-model="state.ruleForm.templateCode" class="input-width" placeholder="任务ID"></el-input>
						</el-form-item>
						<el-form-item label="创建人">
							<el-input v-model="state.ruleForm.createByName" class="input-width" placeholder="创建人"></el-input>
						</el-form-item>
						<el-form-item label="创建日期">
							<el-date-picker v-model="state.ruleForm.createDate" type="datetimerange" :picker-options="state.pickerOptions" range-separator="至"
								start-placeholder="开始日期" end-placeholder="结束日期" align="right">
							</el-date-picker>
						</el-form-item>
					</div>
				</el-form>
			</div>
		</el-card>
		<!-- </el-card> -->
		<el-card style="margin-top: 10px;margin-bottom: 10px;--el-card-padding: 10px;padding-left:12px;padding-right:12px" shadow="hover">
			<div class="bar_btn_div" style="margin-top: 0px;margin-buttom:margin-bottom: 10px;">
				<div class="title_div">
					<div><b>操作</b></div>
				</div>
				<el-button-group class="btn-add">

					<el-button type="primary" @click="saveOrUpdate('create')">创建模板</el-button>
				</el-button-group>
			</div>
		</el-card>
		<el-card style="margin-top: 10px;" shadow="hover" class="layout-padding-auto">
			<el-table size="default" :data="state.dataList" style="width: 100%" :header-cell-class-name="handleHeaderClass" @sort-change="onSortHandler"
				:default-sort="{ prop: 'createDate', order: 'descending' }">
				<el-table-column align="center" label="模板编码" width="150" sortable="custom" prop="templateCode">
				</el-table-column>
				<el-table-column align="center" prop="fileId" label="文件名">
					<template #default="scope">
						<a href="javascript:void(0);" @click="downloadFile(scope.row.fileId, scope.row.templateCode)">{{ scope.row.fileId }}</a>
					</template>
				</el-table-column>
				<el-table-column label="状态" prop="status" width="100">
					<template #default="scopeParam">
						<dicItemsETag dicCode="commStatus" :value="scopeParam.row.status" :key="scopeParam.row.status"
							:type="scopeParam.row.status === 1 ? 'success' : 'warning'" />
					</template>
				</el-table-column>

				<el-table-column label="模板类型" prop="templateType" width="120">
					<template #default="scopeParam">
						<el-select v-model="scopeParam.row.templateType" disabled="true">
							<dicItemsSelectOptions dicCode="导出模板类型" data-type="Int" :withNullValue="false" />
						</el-select>
					</template>
				</el-table-column>
				<el-table-column label="创建人" prop="createByName" width="120"></el-table-column>
				<el-table-column label="创建日期" prop="createDate" sortable="custom" width="240">
				</el-table-column>
				<el-table-column label="更新人" prop="updateByName" width="120"></el-table-column>
				<el-table-column label="更新日期" prop="updateDate" width="240" sortable="custom"></el-table-column>
				<el-table-column label="操作" fixed="right" width="120">
					<template #default="scopeParam">
						<el-button type="primary" @click="saveOrUpdate('update', scopeParam.row)">修改模板</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-card>
		<el-pagination @size-change="onHandleSizeChange" @current-change="onHandleCurrentChange" class="mt15" :pager-count="5" :page-sizes="[10, 20, 30]"
			v-model:current-page="state.page" background v-model:page-size="state.limit" layout="total, sizes, prev, pager, next, jumper" :total="state.total">
		</el-pagination>

		<saveOrUpdateTemplate ref="saveOrUpdatePage" :refreshFunction="state.refreshFunction"></saveOrUpdateTemplate>
	</div>
</template>

<script setup lang="ts" name="imexportPage">

import { onMounted, reactive, defineAsyncComponent, ref } from 'vue';
import { ElMessage } from 'element-plus';

import { imexportApi } from '/@/api/imexport/index';

import { camelToUnderline } from '/@/utils/StringFormat';

const dicItemsETag = defineAsyncComponent(() => import('/@/components/dic/dicItemsETag.vue'));
const dicItemsSelectOptions = defineAsyncComponent(() => import('/@/components/dic/dicItemsSelectOptions.vue'));

const saveOrUpdateTemplate = defineAsyncComponent(() => import('/@/views/export/template/saveOrUpdateTemplate.vue'));

import { formatDate } from '/@/utils/formatTime';

const saveOrUpdatePage = ref();


const saveOrUpdate = (pageType: string, data: any) => {
	saveOrUpdatePage.value.initData(pageType, data);
};

const ruleForm = {
	createByName: null,
	createDate: null,
	fileId: null,
	status: null,
	templateCode: null,
	templateType: null,
	updateByName: null,
	updateDate: null,
};

const initQueryParams = {
	page: 1,
	limit: 10,
	total: 0,
	start: 0,
	ruleForm
};

let state = reactive({
	page: 1,
	limit: 10,
	total: 0,
	dataList: [] as any,
	sorts: { "createDate": "descending" },
	ruleForm: {
		createByName: null,
		createDate: [] as any,
		fileId: null,
		status: null,
		templateCode: null,
		templateType: null,
		updateByName: null,
		updateDate: null,
	},
	pickerOptions: {
		shortcuts: [
			{
				text: "最近一周",
				onClick(picker: any) {
					const end = new Date();
					const start = new Date();
					start.setTime(
						start.getTime() - 3600 * 1000 * 24 * 7
					);
					picker.$emit("pick", [start, end]);
				},
			},
			{
				text: "最近一个月",
				onClick(picker: any) {
					const end = new Date();
					const start = new Date();
					start.setTime(
						start.getTime() - 3600 * 1000 * 24 * 30
					);
					picker.$emit("pick", [start, end]);
				},
			},
			{
				text: "最近三个月",
				onClick(picker: any) {
					const end = new Date();
					const start = new Date();
					start.setTime(
						start.getTime() - 3600 * 1000 * 24 * 90
					);
					picker.$emit("pick", [start, end]);
				},
			},
		],
	},
	refreshFunction: () => {
		refresh();
	}

});

const handleHeaderClass = (column: any) => {
	if (column.column.property) {
		column.column.order = state.sorts[column.column.property];
	}
};
const sortsStr = () => {
	var result = "";
	for (var prop in state.sorts) {
		result += camelToUnderline(prop) + (state.sorts[prop] == "descending" ? " desc," : " asc,")
	}
	if (result == "") {
		return null;
	}
	return result.substring(0, result.length - 1)
};
const onSortHandler = (column: any) => {
	if (column.order) {
		state.sorts[column.prop] = column.order
	} else if (state.sorts[column.prop]) {
		delete state.sorts[column.prop];
	}
	getExportTemplateList();
};

const getExportTemplateList = async () => {
	let vo = {
		page: state.page,
		limit: state.limit,
		sorts: sortsStr()
	} as any;

	let queryParams = {
		createDate: null as any,
	};


	for (let prop in state.ruleForm) {
		if (prop == "createDate") {
			if (state.ruleForm.createDate?.length > 1) {
				queryParams.createDate = state.ruleForm.createDate[0].getTime() + "," + state.ruleForm.createDate[1].getTime();
			}
		} else {
			if (state.ruleForm[prop]) {
				queryParams[prop] = state.ruleForm[prop];
			}
		}
	}

	let tempList = await imexportApi().getExportTemplate(Object.assign({}, vo, queryParams));
	state.dataList = tempList.list;
	state.total = tempList.total;

	ElMessage.success({
		message: "查询成功，共计" + state.total + "条",
		type: 'success',
	});
}

// 分页改变
const onHandleSizeChange = (val: number) => {

	state.limit = val;
	getExportTemplateList();
};
// 分页改变
const onHandleCurrentChange = (val: number) => {
	state.page = val;
	getExportTemplateList();
};


const handleResetSearch = () => {
	state = Object.assign(state, initQueryParams)
	state.ruleForm = ruleForm;
	getExportTemplateList();
}


const refresh = () => {
	getExportTemplateList();
}



const downloadFile = async (_id: String, filename: string) => {
	try {
		await imexportApi().downloadFile("admin", _id).then(response => {
			if (window.navigator.msSaveOrOpenBlob) {
				navigator.msSaveBlob(response, filename);
			} else {
				var link = document.createElement("a");
				link.href = window.URL.createObjectURL(response);
				link.download = filename;
				link.click();
				window.URL.revokeObjectURL(link.href);
			}
		});

		ElMessage.success({ message: '下载成功', type: 'success', });
	} catch (error) {
		ElMessage.error("文件下载失败，请检查!");
	}

}
// 页面加载时
onMounted(() => {
	getExportTemplateList()
});



</script>
<style scoped lang="scss">
.el-form .el-form-item:last-of-type {
	margin-bottom: 22px !important;
}

.bar_tools {
	display: flex;
	flex-direction: row-reverse;
	margin-bottom: 10px;
}


.bar_btn_div {
	display: flex;
	padding: 20px;
	border: 1px solid #ebeef5;
	align-items: center;
	justify-content: space-between;
	border-radius: 5px 5px 0px 0px;
	padding: 10px;
	padding-left: 20px;
	padding-right: 20px;

	.title_div {
		display: flex;
		font-size: 16px;

		&>div {
			margin-right: 10px;
		}
	}
}

.search_div {
	border: 1px solid #ebeef5;
	border-top: 0px;
	border-radius: 0px 0px 5px 5px;
	padding: 20px;
	padding-bottom: 0px;
}

.card {
	overflow-y: auto
}
</style>